package com.neutech.shop.controller;

import com.neutech.shop.entity.Admin;
import com.neutech.shop.entity.User;
import com.neutech.shop.service.AdminService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @author Neuedu-远哥
 * @version 1.0
 * @date 2021/9/15 15:49
 */
@Controller
@RequestMapping("/back/admin")
public class AdminController {
    @Resource
    private AdminService adminService;
    @RequestMapping("/list")
    public String selectAll(ModelMap map){
        List<Admin> admins = adminService.selectAll();
        map.addAttribute("admins",admins);
        return "admin_list.jsp";
    }
    @RequestMapping("/load")
    public String load(Long id,ModelMap map){
        Admin admin = adminService.selectById(id);
        map.addAttribute("admin",admin);
        return "admin_load.jsp";
    }

    @RequestMapping("/update")
    public String update(Admin admin,String originPassword, String newPassword){

        adminService.update(admin,originPassword,newPassword);

        return "redirect:list";
    }
    @RequestMapping("/delete")
    public String delete(Long id){
        adminService.delete(id);
        return "redirect:list";
    }
    @RequestMapping("/resetPassword")
    public String resetPassword(Long id){
        adminService.resetPassword(id);
        return "redirect:list";
    }

    /**
     * 用户登录
     * @param admin
     * @param session
     * @return
     */
    @RequestMapping("/login")
    public String login(Admin admin, String code, HttpSession session, ModelMap map, HttpServletRequest request){
        boolean success = adminService.login(admin);
        // /cq_shop
        if(success){
            // 登录成功的情况
            if(session.getAttribute("code").equals(code)){
                session.setAttribute("admin",admin);
                return "redirect:/back/index.jsp";
            }else{
                // 用户名密码正确，验证码错误
                map.addAttribute("error_code_msg","验证码错误");
                return "/back/login.jsp";
            }
        } else{
            // 登录失败
            map.addAttribute("error_msg","用户名或密码错误");
            // 重定向到登录页面 去登录
            return "/back/login.jsp";
        }
    }
    @RequestMapping("/logout")
    public String logout(HttpSession session){
        // 让seesion马上失效
        session.invalidate();
        return "redirect:/back/login.jsp";
    }

}
